package by.bucha.testproject.fragments;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import by.bucha.testproject.R;
import by.bucha.testproject.content.bo.workers.LeaderModel;
import by.bucha.testproject.content.bo.workers.SimpleWorkerModel;
import by.bucha.testproject.content.contract.TaskContract;
import by.bucha.testproject.service.ApplicationService;
import by.bucha.testproject.service.ServiceCallbackListener;
import by.bucha.testproject.service.handlers.BaseHandler;
import by.bucha.testproject.utils.TaskApplication;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class EditPersonFragment extends Fragment implements
		ServiceCallbackListener {

	public EditPersonFragment() {
	}

	public static final String EXTRA_MODEL_ID = "id of model which you want edit";

	private EditText mEditName;
	private EditText mEditSurname;
	private EditText mEditPatronymic;
	private EditText mEditSalary;
	private EditText mEditStartTimeReception;
	private EditText mEditEndTimeReception;
	private EditText mEditLunch;
	private EditText mEditWorkspaceNumber;

	private RadioButton mLeaderModelRadio;

	private RadioButton mSimpleWorkerModelRadio;

	private String mModelId;

	private int mRequestId;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setHasOptionsMenu(true);

		Bundle bundle = this.getArguments();
		mModelId = bundle.getString(EXTRA_MODEL_ID);
	}

	@Override
	public void onPause() {
		super.onPause();
		TaskApplication.getServiceHelper().removeListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		TaskApplication.getServiceHelper().addListener(this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_bar_menu_items_fragment_edit_person_item_save_changes:
			if (isValidInput()) {
				if (mSimpleWorkerModelRadio.isChecked()) {
					SimpleWorkerModel model = getSimpleWorkerModel();

					Uri uri = TaskContract.createUriWithSelection(mModelId,
							TaskContract.WorkerColumns.CONTENT_URI);

					String serializedModel = new Gson().toJson(model);

					mRequestId = TaskApplication
							.getServiceHelper()
							.updateDatabase(
									uri,
									TaskContract.WorkerColumns.WORKER_ID,
									null,
									serializedModel,
									TaskContract.WorkerColumns.SIMPLE_WORKER_TABLE_TYPE);

				} else if (mLeaderModelRadio.isChecked()) {
					LeaderModel model = getLeaderModel();

					Uri uri = TaskContract.createUriWithSelection(mModelId,
							TaskContract.WorkerColumns.CONTENT_URI);

					String serializedModel = new Gson().toJson(model);

					mRequestId = TaskApplication
							.getServiceHelper()
							.updateDatabase(
									uri,
									TaskContract.WorkerColumns.WORKER_ID,
									null,
									serializedModel,
									TaskContract.WorkerColumns.LEADER_TABLE_TYPE);
				}
			}
			return true;
		case R.id.action_bar_menu_items_fragment_edit_person_item_back:
			closeFragment();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		menu.clear();
		inflater.inflate(R.menu.action_bar_menu_items_fragment_edit_person,
				menu);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.view_fragment_add_person,
				container, false);
		initView(view);

		RadioGroup radiogroup = (RadioGroup) view
				.findViewById(R.id.view_fragment_add_person_radio_group);

		radiogroup
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						switch (checkedId) {
						case R.id.view_fragment_add_person_radio_leader:
							view.findViewById(
									R.id.view_fragment_add_person_simple_user_layout)
									.setVisibility(View.GONE);
							view.findViewById(
									R.id.view_fragment_add_person_leader_layout)
									.setVisibility(View.VISIBLE);
							break;
						case R.id.view_fragment_add_person_radio_simple_user:
							view.findViewById(
									R.id.view_fragment_add_person_simple_user_layout)
									.setVisibility(View.VISIBLE);
							view.findViewById(
									R.id.view_fragment_add_person_leader_layout)
									.setVisibility(View.GONE);
							break;

						default:
							break;
						}
					}
				});

		Uri uri = TaskContract.createUriWithSelection(mModelId,
				TaskContract.WorkerColumns.CONTENT_URI);
		mRequestId = TaskApplication.getServiceHelper().getSingleRow(uri,
				TaskContract.WorkerColumns.WORKER_ID, null, null, null);

		return view;
	}

	@Override
	public void onServiceCallback(int requestId, Intent requestIntent,
			int resultCode, Bundle data) {
		String action = requestIntent.getAction();
		if (resultCode == BaseHandler.FAILURE_RESPONSE
				&& mRequestId == requestId) {
			Toast.makeText(getActivity().getApplicationContext(),
					data.getString(ApplicationService.EXTRA_ON_ERROR),
					Toast.LENGTH_SHORT).show();
		} else if (ApplicationService.ACTION_QUERY.equals(action)
				&& mRequestId == requestId) {

			String dataType = data
					.getString(TaskContract.WorkerColumns.WORKER_TYPE);

			if (dataType.equals(TaskContract.WorkerColumns.LEADER_TABLE_TYPE)) {
				LeaderModel model = new Gson()
						.fromJson(
								data.getString(ApplicationService.EXTRA_QUERY_RESPONSE),
								new TypeToken<LeaderModel>() {
								}.getType());
				setLeaderModelToView(model);
			} else if (dataType
					.equals(TaskContract.WorkerColumns.SIMPLE_WORKER_TABLE_TYPE)) {
				SimpleWorkerModel model = new Gson()
						.fromJson(
								data.getString(ApplicationService.EXTRA_QUERY_RESPONSE),
								new TypeToken<SimpleWorkerModel>() {
								}.getType());
				setSimpleWorkerModelToView(model);
			}
		} else if (ApplicationService.ACTION_UPDATE.equals(action)
				&& mRequestId == requestId) {
			Toast.makeText(getActivity().getApplicationContext(), "EDITED!",
					Toast.LENGTH_SHORT).show();
			closeFragment();
		}
	}

	private void initView(View view) {
		mEditName = (EditText) view
				.findViewById(R.id.view_fragment_add_person_name_input);

		mEditSurname = (EditText) view
				.findViewById(R.id.view_fragment_add_person_surname_input);

		mEditPatronymic = (EditText) view
				.findViewById(R.id.view_fragment_add_person_patronymic_input);

		mEditSalary = (EditText) view
				.findViewById(R.id.view_fragment_add_person_salary_input);

		mEditStartTimeReception = (EditText) view
				.findViewById(R.id.view_fragment_add_person_start_time_reception_input);

		mEditEndTimeReception = (EditText) view
				.findViewById(R.id.view_fragment_add_person_end_time_reception_input);

		mEditLunch = (EditText) view
				.findViewById(R.id.view_fragment_add_person_lunch_input);

		mEditWorkspaceNumber = (EditText) view
				.findViewById(R.id.view_fragment_add_person_workspace_number_input);

		mSimpleWorkerModelRadio = (RadioButton) view
				.findViewById(R.id.view_fragment_add_person_radio_simple_user);
		mLeaderModelRadio = (RadioButton) view
				.findViewById(R.id.view_fragment_add_person_radio_leader);

	}

	private void setLeaderModelToView(LeaderModel leader) {
		mEditName.setText(leader.getName());

		mEditSurname.setText(leader.getSurname());

		mEditPatronymic.setText(leader.getPatronymic());

		mEditSalary.setText(String.valueOf(leader.getSalary()));

		mLeaderModelRadio.setChecked(true);

		mEditStartTimeReception.setText(leader.getStartTimeReception());

		mEditEndTimeReception.setText(leader.getEndTimeReception());
	}

	private void setSimpleWorkerModelToView(SimpleWorkerModel simpleWorker) {
		mEditName.setText(simpleWorker.getName());

		mEditSurname.setText(simpleWorker.getSurname());

		mEditPatronymic.setText(simpleWorker.getPatronymic());

		mEditSalary.setText(String.valueOf(simpleWorker.getSalary()));

		mSimpleWorkerModelRadio.setChecked(true);

		mEditLunch.setText(simpleWorker.getLunchTime());

		mEditWorkspaceNumber.setText(String.valueOf(simpleWorker
				.getWorkplaceNumber()));

	}

	private void closeFragment() {
		getActivity().getSupportFragmentManager().popBackStack();
	}

	private Boolean isValidInput() {
		Boolean isInpuValid = true;
		if (mEditName.getText().length() == 0) {
			String nameErrorMessage = getResources()
					.getString(
							R.string.add_person_fragment_name_empty_edit_text_errore_message);
			mEditName.setError(nameErrorMessage);
			isInpuValid = false;
		}
		if (mEditSurname.getText().length() == 0) {
			String surnameErrorMessage = getResources()
					.getString(
							R.string.add_person_fragment_surname_empty_edit_text_errore_message);
			mEditSurname.setError(surnameErrorMessage);
			isInpuValid = false;
		}
		if (mEditPatronymic.getText().length() == 0) {
			String patronymicErrorMessage = getResources()
					.getString(
							R.string.add_person_fragment_patronymic_empty_edit_text_errore_message);
			mEditPatronymic.setError(patronymicErrorMessage);
			isInpuValid = false;
		}
		if (mEditSalary.getText().length() == 0) {
			String salaryErrorMessage = getResources()
					.getString(
							R.string.add_person_fragment_salary_empty_edit_text_errore_message);
			mEditSalary.setError(salaryErrorMessage);
			isInpuValid = false;
		}
		if (mLeaderModelRadio.isChecked()) {
			if (mEditEndTimeReception.getText().length() == 0) {
				String endTimeReceptionErrorMessage = getResources()
						.getString(
								R.string.add_person_fragment_end_time_reception_empty_edit_text_errore_message);
				mEditEndTimeReception.setError(endTimeReceptionErrorMessage);
				isInpuValid = false;
			}
			if (mEditStartTimeReception.getText().length() == 0) {
				String startTimeReceptionErrorMessage = getResources()
						.getString(
								R.string.add_person_fragment_start_time_reception_edit_text_errore_message);
				mEditStartTimeReception
						.setError(startTimeReceptionErrorMessage);
				isInpuValid = false;
			}
		} else if (mSimpleWorkerModelRadio.isChecked()) {

			if (mEditLunch.getText().length() == 0) {
				String lunchErrorMessage = getResources()
						.getString(
								R.string.add_person_fragment_lunch_time_empty_edit_text_errore_message);
				mEditLunch.setError(lunchErrorMessage);
				isInpuValid = false;
			}

			if (mEditWorkspaceNumber.getText().length() == 0) {
				String workspaceNumberErrorMessage = getResources()
						.getString(
								R.string.add_person_fragment_workspace_number_empty_edit_text_errore_message);
				mEditWorkspaceNumber.setError(workspaceNumberErrorMessage);
				isInpuValid = false;
			}
		}
		return isInpuValid;
	}

	private LeaderModel getLeaderModel() {
		LeaderModel model = new LeaderModel();

		model.setName(String.valueOf(mEditName.getText()));
		model.setEndTimeReception(String.valueOf(mEditEndTimeReception
				.getText()));
		model.setPatronymic(String.valueOf(mEditPatronymic.getText()));
		model.setSalary(Integer.parseInt(String.valueOf(mEditSalary.getText())));
		model.setStartTimeReception(String.valueOf(mEditStartTimeReception
				.getText()));
		model.setSurname(String.valueOf(mEditSurname.getText()));

		return model;
	}

	private SimpleWorkerModel getSimpleWorkerModel() {
		SimpleWorkerModel model = new SimpleWorkerModel();

		model.setName(String.valueOf(mEditName.getText()));
		model.setWorkplaceNumber(Integer.parseInt(String
				.valueOf(mEditWorkspaceNumber.getText())));
		model.setPatronymic(String.valueOf(mEditPatronymic.getText()));
		model.setSalary(Integer.parseInt(String.valueOf(mEditSalary.getText())));
		model.setLaunchTime(String.valueOf(mEditLunch.getText()));
		model.setSurname(String.valueOf(mEditSurname.getText()));

		return model;
	}

}
